use askama_axum::{IntoResponse, Template};
use axum::{extract::State, response::{Html, Redirect}, Form};
use tower_cookies::Cookies;
use tower_sessions::Session;
use crate::core::xerror::{GLOBALERROR, XErrors};
use crate::core::AppState;
use crate::types::common::Breadcrumb;
use crate::services::backend::config_service::ConfigService;
use crate::types::backend::config_type::ConfigForm;
use super::{AdminSession, ErrorTemplate};



#[derive(Template)]
#[template(path = "backend/config/form.html")]
struct ConfigFormTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    data: ConfigForm
}


/// 修改配置表单
pub async fn edit_config_handler(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let res = ConfigService::get_config(&state.db).await;
    let breadcrumb = Breadcrumb {
        title: "配置管理".to_string(),
        sub_title: "修改配置".to_string(),
    };
    match res {
        Ok(data) => {
            let template = ConfigFormTemplate {
                auth,
                breadcrumb,
                data   
            };
            return Html(template.render().unwrap());
        },
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string(),
            };
            return Html(template.render().unwrap());
        }
    }
}

/// 修改配置操作
pub async fn update_config_handler(
    State(state): State<AppState>, 
    cookies: Cookies, 
    Form(form): Form<ConfigForm>) -> Redirect {
    let error = XErrors::new();
    // 名称不能为空
    if form.name.is_empty() {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to("/backend/config/edit");
    }

    let res = ConfigService::update_config(&state.db, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::UPDATESUCCESS, "".to_string());
            return Redirect::to("/backend/config/edit");
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::UPDATEFAILED, db_error);
            return Redirect::to("/backend/config/edit");
        }
    }
}
